package com.cutie.core.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DBManager {

	public static void executeUpdate(String sql, Object[] data) throws SQLException{
		Connection con = null;
		PreparedStatement pstmt = null;
		try{
			con = DatabaseConnectionPool.getConnection();
			pstmt = con.prepareStatement(sql);
			fillData(pstmt,data);
			pstmt.executeUpdate();
		}catch(SQLException e){
			e.printStackTrace();
			throw e;
		}finally{
			DatabaseUtils.close(null, pstmt, con);
		}
	}
	
	public static Object executeQuery(String sql, Object[] data, IBuilder iResult) throws SQLException{
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try{
			con = DatabaseConnectionPool.getConnection();
			pstmt = con.prepareStatement(sql);
			fillData(pstmt,data);
			rs = pstmt.executeQuery();
			return iResult.build(rs);
		}catch(SQLException e){
			e.printStackTrace();
			throw e;
		}finally{
			DatabaseUtils.close(rs, pstmt, con);
		}
	}
	
	private static void fillData(PreparedStatement pstmt, Object[] data) throws SQLException{
		for(int i=0; i<data.length ; i++){
			Object o = data[i];
			pstmt.setObject(i+1, o);
		}
	}
}
